package com.cwt_taxi_xa.protocol;

import android.graphics.Bitmap;
import android.util.Log;

import com.cwt_taxi_xa.ActivityWaitQD;
import com.cwt_taxi_xa.MainApplication;
import com.cwt_taxi_xa.constants.Constants;
import com.cwt_taxi_xa.data.SijiInfo;
import com.cwt_taxi_xa.protocol.card.CardManager;
import com.cwt_taxi_xa.service.SerialPortService;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.Tools;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * TSM读卡器
 *
 * @author Administrator
 *
 */
public class CardUtil {
	final static String TAG = "CardUtil";
	public static String[] infoKeys = {
			"学期号",
			"学号",
			"身份证号",
			"从业资格证号",
			"姓名",
			"地址",
			"年龄",
			"政治面貌",
			"年度审核状态",
			"从业资格证类别",
			"驾照号",
			"驾驶员性质",
			"驾照档案编号",
			"驾照签发日期",
			"资格证初次发证日期",
			"发证日期",
			"资格证有效期",
			"未知",
			"监督电话",
			"未知",
			"预留",
			"服务资格证状态",
			"发证日期",
			"有效期",
			"投诉电话",
			"核发机关",
			"驾驶员代码",
			"准驾车辆范围",
			"预留",
			"服务星级",
			"评定日期",
			"年度得分",
			"其他",
			"服务单位代码标识",
			"服务单位简称",
			"变更日期",
			"准驾车牌列表",
			"下次回单位培训时间",
			"预留",
			"预留",
	};


	/**
	 * 程序启动后一直处于自动读卡状态，即在通用timer每秒读一次，当要用到刷卡模块其他功能时，可以用这个开关暂时关闭自动读卡
	 */
	public static boolean autoRead = true;


	//临时当前刷卡获取的司机信息
	public static String Code_card = "";


	public static void onCardReceive(byte[] data, int size) {

//		AppLog.e("读卡器数据：" + Tools.parseByte2HexStr(Tools.byteTobyte(data, 0, size)));

		NianBaoUtil.nbtsm(data, size);

	}

	public static int jieduan = 0;
	public static int pcfileindex = 0;
	public static int ewfileindex = 0;
	public static int EF0B_index = 1;
	public static String[] EF0B_first;
	public static long signtime = 0;
	//二次读卡临时信息
	public static SijiInfo  sijiInfo;

	public static CardManager mCardManager = new CardManager();

	public static void onReceOrder(byte[] data, int size) {

		byte[] order = new byte[size];
		System.arraycopy(data, 0, order, 0, size);


		String order_str = Tools.parseByte2HexStr(order);
		Log.e("读卡器数据-完整数据包：" + size, "-------------"+order_str);

		AppLog.savelog("接收到读卡器数据-----------------："+order_str);

		boolean jy = datajy(order);
//		Log.e("读卡器数据-校验结果", "" + jy);

		if (jy) {

			// 905读卡器
			try {
				String mid = Tools.parseByte2HexStr(Tools.byteTobyte(order, 6, 2));
				AppLog.d("------------- mid:" + mid);

				String result = Tools.parseByte2HexStr(Tools.byteTobyte(order, order.length - 5, 2));
				AppLog.d("------------- result:" + result);

				//AppLog.e("------------- Tools.byteTobyte " + Tools.parseByte2HexStr(Tools.byteTobyte(order, 8, order.length - 5 -6 -2)));
				//获取有效数据区	Tools.byteTobyte(order, 8, order.length - 5 -6 -2)
				//考虑到串口测试,先不处理数据
				mCardManager.receivePackage(mid, result, order);//
			} catch (Exception e) {

			}

		} else {
			MainApplication.topActivity.myToast("校验失败");
		}

	}

	public static void readEnd(){
		pcfileindex = 0;
		ewfileindex = 0;
		jieduan = 0;
		AppLog.saveFile_clear();
	}


	public static long lasttime = 0;
	public static void checkLocaInfo(String qiyeCode_card2) {
		if(Constants.sijiinfo!=null&&Constants.sijiinfo.getCardnum().equals(qiyeCode_card2)){
			Constants.sijiNow = true;
			return;
		}

		Constants.sijiNow = false;


		if(System.currentTimeMillis()-lasttime<5000){
			return;
		}
		lasttime = System.currentTimeMillis();

//		File file = new File(Constants.SDPath+qiyeCode_card2);
//		if(file.exists()){
//			Constants.sijiinfo = VersionBiz.getSijiInfo(qiyeCode_card2);
//			Constants.sijiNow = true;
//			return;
//		}

//		VersionBiz.doCheckSJInfor(qiyeCode_card2, new checkSJinfor() {
//			@Override
//			public void onInfor() {
//				// TODO Auto-generated method stub
//
//			}
//		});

	}


	interface onInforReturn{
		void oninforrerurn();
	}

	/**
	 * 解析卡数据为司机信息
	 *
	 * @param data
	 * @return 类型（司机-1，管理者-2）：企业许可证：司机从业资格证：车牌号
	 */
	public static String[] parseCardData2Info(byte[] data) {
		for (int i = 0; i < data.length; i++) {
			data[i] = (byte) (data[i] + (i % 2 + 1));
		}
		int l = data[0];
		byte[] result = new byte[l];
		System.arraycopy(data, 1, result, 0, l);
		// String type = ss[0];
		// String QYCODE = ss[1];
		// String SJCODE = ss[2];
		// String CARCODE = ss[3];
		// tv1.setText("类型（司机-1，管理者-2）："+type+"\n企业许可证："+QYCODE+"\n司机从业资格证："+SJCODE+"\n车牌号："+CARCODE);
		return new String(result).split("-");
	}

	/**
	 * 司机信息编码
	 *
	 * @param info
	 *            类型-企业许可证-从业资格证-车牌号
	 * @return 16*6字节数据包
	 */
	public static byte[] parseInfo2CardData(String info) {
		byte[] data = info.getBytes();
		byte[] data2 = new byte[data.length + 1];
		data2[0] = (byte) data.length;
		System.arraycopy(data, 0, data2, 1, data.length);
		for (int i = 0; i < data2.length; i++) {
			data2[i] = (byte) (data2[i] - (i % 2 + 1));
		}
		byte[] result = new byte[16 * 6];
		System.arraycopy(data2, 0, result, 0, data2.length);
		for (int i = 0; i < result.length; i++) {
			if (i >= data2.length) {
				result[i] = 0;
			}
		}
		return result;
	}


	public static void readCardNumber(){
		SerialPortService.getInstance().sendSerialData2(Tools.parseHexStr2Byte("55 AA 00 04 03 00 00 20 27 55 AA"));
	}

	/**
	 * 读卡 20 01 00 00 00 01 00 FF FF FF FF FF FF
	 */
	public static void readCard(int size) {
		byte[] result = new byte[13];
		result[0] = 0x20;
		result[1] = 0x01;
		result[2] = 0x00;
		result[3] = 0x00;
		result[4] = (byte) (size % 256);
		result[5] = (byte) (size / 256);
		result[6] = 0x00;
		System.arraycopy(Tools.parseHexStr2Byte("FF FF FF FF FF FF"), 0, result, 7, 6);
		if(SerialPortService.getInstance()!=null){
			SerialPortService.getInstance().sendSerialData2(cardjy(result));
		}
	}

	/**
	 * 写卡 20 02 命令 00 00 起始地址 00 01 写卡长度 小端 00 密码类型 FF FF FF FF FF FF NN NN 数据
	 */
	public static void setCardData(byte[] data) {
		byte[] result = new byte[13 + data.length];
		result[0] = 0x20;
		result[1] = 0x02;
		result[2] = 0x00;
		result[3] = 0x00;
		result[4] = (byte) (data.length % 256);
		result[5] = (byte) (data.length / 256);
		result[6] = 0x00;
		System.arraycopy(Tools.parseHexStr2Byte("FF FF FF FF FF FF"), 0, result, 7, 6);
		System.arraycopy(data, 0, result, 13, data.length);
		SerialPortService.getInstance().sendSerialData2(cardjy(result));
	}

	/**
	 * 自己家读卡器
	 *
	 * 添加包头尾、长度、0000、校验码
	 *
	 * @param data
	 * @return
	 */
	public static byte[] cardjy(byte[] data) {
		byte[] bs = new byte[data.length + 9];
		bs[0] = 0x55;
		bs[1] = (byte) 0xAA;
		bs[2] = (byte) ((data.length + 2) / 256);
		bs[3] = (byte) ((data.length + 2) % 256);
		bs[4] = 0;
		bs[5] = 0;
		bs[bs.length - 3] = 0;
		bs[bs.length - 2] = 0x55;
		bs[bs.length - 1] = (byte) 0xAA;
		System.arraycopy(data, 0, bs, 6, data.length);

		for (int i = 2; i < bs.length - 3; i++) {
			bs[bs.length - 3] = (byte) (bs[bs.length - 3] ^ bs[i]);
		}
		return bs;
	}

	public static void sendTsm905Data(int order, byte[] data){
		if(data!=null&&data.length>0){
			byte[] result = new byte[data.length+2];
			System.arraycopy(Tools.int2Bytes2(order, 2), 0, result, 0, 2);
			System.arraycopy(data, 0, result, 2, data.length);
			SerialPortService.getInstance().sendSerialData2(cardjy2(result));
		}else{
			SerialPortService.getInstance().sendSerialData2(cardjy2(Tools.int2Bytes2(order, 2)));
		}
	}

	//当listener不为空时，判断为签退检测
	public static CheckCardListener listener;
	public static void CheckCard(CheckCardListener listener){
		CardUtil.listener = listener;
		mCardManager.changeSignOffState();
		mCardManager.startAndRead();
		//CardUtil.sendTsm905Data(0x0015, Tools.parseHexStr2Byte("00"));
		//SerialPortService.getInstance().sendSerialData2(cardjy2(Tools.int2Bytes2(0x0020, 2)));
	}

	public static byte[] getTsm905Data(int order, byte[] data){
		if(data!=null&&data.length>0){
			byte[] result = new byte[data.length+2];
			System.arraycopy(Tools.int2Bytes2(order, 2), 0, result, 0, 2);
			System.arraycopy(data, 0, result, 2, data.length);
			return cardjy2(result);
		}else{
			return cardjy2(Tools.int2Bytes2(order, 2));
		}
	}

	/**
	 * tsm905
	 *
	 * 添加包头尾、长度、0000、校验码
	 *
	 * @param data
	 * @return
	 */
	public static byte[] cardjy2(byte[] data) {
		byte[] bs = new byte[data.length + 9];
		bs[0] = 0x55;
		bs[1] = (byte) 0xAA;
		bs[2] = (byte) ((data.length + 2) / 256);
		bs[3] = (byte) ((data.length + 2) % 256);
		bs[4] = 3;
		bs[5] = 0;
		bs[bs.length - 3] = 0;
		bs[bs.length - 2] = 0x55;
		bs[bs.length - 1] = (byte) 0xAA;
		System.arraycopy(data, 0, bs, 6, data.length);

		for (int i = 2; i < bs.length - 3; i++) {
			bs[bs.length - 3] = (byte) (bs[bs.length - 3] ^ bs[i]);
		}
		return bs;
	}





	/**
	 * 校验上行数据
	 *
	 * @param data
	 * @return
	 */
	public static boolean datajy(byte[] data) {

		byte result = 0;
		for (int i = 2; i < data.length - 3; i++) {
			result = (byte) (result ^ data[i]);
		}

		return data[data.length - 3] == result;
	}

	/**
	 * 裁剪图片
	 */
	public static Bitmap getewm2(Bitmap bitmap){
		return Bitmap.createBitmap(bitmap, 390, 890, 982, 972);
	}

	public static byte[] readStream(String path) throws Exception{
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5 * 1000);
		conn.setRequestMethod("GET");
		if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
			InputStream inStream = conn.getInputStream();
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while( (len=inStream.read(buffer)) != -1){
				outStream.write(buffer, 0, len);
			}
			outStream.close();
			inStream.close();
			return outStream.toByteArray();
		}else{
			return null;
		}

	}


	public synchronized static void cardCache(String[] ss_EF08){
		if(ss_EF08 != null){
			sijiInfo = new  SijiInfo();
			//保存司机文本信息到本地
			sijiInfo = new SijiInfo();

			//姓名
			sijiInfo.setName(ss_EF08[4]);

			//司机号
			sijiInfo.setSijicode(ss_EF08[3]);

			//企业号
//			Constants.sijiinfo.setQiyecode(ss_info2[12]);
			sijiInfo.setQiyecode("12345");

			//资格证有效期
			sijiInfo.setCertificateData(ss_EF08[16]);

			//星级1-5
			try {
				sijiInfo.setStar(Integer.parseInt(ss_EF08[19])+2);
			} catch (Exception e) {
				sijiInfo.setStar(5);
			}

			//监督电话
			sijiInfo.setMobile(ss_EF08[18]);
			//卡号
			//sijiInfo.setCardnum("000000");
			//签到新加(十九项) 2019-06-04-------------------------------------

			try {
				sijiInfo.setTermNumber(Integer.parseInt(ss_EF08[0]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			try {
				sijiInfo.setStudentID(Integer.parseInt(ss_EF08[1]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			sijiInfo.setIdentityNumber(ss_EF08[2]);
			sijiInfo.setAddress(ss_EF08[5]);

			try {
				sijiInfo.setAge(Integer.parseInt(ss_EF08[6]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}


			try {
				//政治面貌
				sijiInfo.setPoliticalStatus(Integer.parseInt(ss_EF08[7]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			try {
				//年度审核
				sijiInfo.setAnnualAudit(Integer.parseInt(ss_EF08[8]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			try {
				//从业资格证类别
				sijiInfo.setCertificateType(Integer.parseInt(ss_EF08[9]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			//驾照号
			sijiInfo.setDriverLicense(ss_EF08[10]);

			try {
				//驾驶员性质
				sijiInfo.setDriverType(Integer.parseInt(ss_EF08[11]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//驾照档案编号
			sijiInfo.setDriverLicenseNumber(ss_EF08[12]);

			//驾照签发日期
			sijiInfo.setDriverLicenseCD(ss_EF08[13]);

			//资格证初次发证日期
			sijiInfo.setCertificateCD(ss_EF08[14]);
			//发证日期
			sijiInfo.setCardCD(ss_EF08[15]);
			try {
				//从业资格证状态
				sijiInfo.setCertificateState(Integer.parseInt(ss_EF08[17]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

	public static void cardServerCache(String[] EF0B_first){
		if(sijiInfo != null && EF0B_first != null && EF0B_first.length > 6){
			//所属公司
			sijiInfo.setCompanyname(EF0B_first[0]);
			//车牌号
			sijiInfo.setCardnum(EF0B_first[1]);

			try {
				sijiInfo.setSupervCardState(Integer.parseInt(EF0B_first[2]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				sijiInfo.setSupervCardState(0);
			}

			try {
				sijiInfo.setSupervCardType(Integer.parseInt(EF0B_first[3]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				sijiInfo.setSupervCardType(0);
			}

			sijiInfo.setSupervCardSDate(EF0B_first[4]);
			sijiInfo.setSupervCardDDate(EF0B_first[5]);
		}
	}

	public static boolean hasReadCard(){
		boolean result = false;
		if(sijiInfo != null){
			String sijiCode = sijiInfo.getSijicode();
			if(ActivityWaitQD.getSiJiIndex(sijiCode)>-1){
				result = true;
			}
		}
		return result;
	}


	public static String readCard(){
		String result = "";
		if(sijiInfo != null){
			result = sijiInfo.getSijicode();
		}
		return result;
	}

	//用于签退时检测读卡
	public interface CheckCardListener{
		public void onCardUnExist();
		public void onReadCard(String sijiCode);
	}





}
